package dflow.repository.custom;

import dflow.domain.Blog;
import dflow.domain.Dto.UserWithBlogs;
import dflow.domain.QBlog;
import dflow.domain.QUser;
import dflow.domain.User;
import dflow.repository.BaseRepository;
import com.querydsl.core.Tuple;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import dflow.util.ContainerUtil;
import org.springframework.data.domain.PageRequest;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by YMY-KF on 2017/7/11.
 */
public class UserRepositoryImpl extends BaseRepository implements UserRepositoryCus {

    /*
    * 用户+博客列表（只获取有博客的用户）*/
    public List<UserWithBlogs> getUserWithBlog(Predicate predicate, PageRequest pageRequest){
        JPAQueryFactory queryFactory = new JPAQueryFactory(em);
        QUser qUser=QUser.user;
        QBlog qBlog=QBlog.blog;
        JPAQuery<Tuple> jpaQuery = queryFactory.select(qUser,qBlog)
                .from(qUser)
                .rightJoin(qBlog)
                .on(qBlog.user_id.intValue().eq(qUser.id.intValue()))
                .offset(pageRequest.getOffset())
                .limit(pageRequest.getPageSize());
        //jpaQuery.where(predicate);
        List<Tuple> list= jpaQuery.fetch();
        //整理数据结构
        List<UserWithBlogs> res =new ArrayList<UserWithBlogs>();
        for (Tuple row : list) {
            User user=row.get(qUser);
            Blog blog=row.get(qBlog);
            //Tuple 一条blog,一个user, 一个用户多个blog时user会重复
            //根据id 找到res中已存在的user
            UserWithBlogs ub=ContainerUtil.getItemById(res,user.getId());
            if(null==ub){
                ub=new UserWithBlogs(user.getId(),user.getNickname());
                res.add(ub);
            }
            ub.getBlogs().add(blog);
        }

        return res;
    }

}
